﻿var LookUpTime = null;
var PrevVal = null;
var PrevValChange = null;
var Currency = ["US", "CA"];
var AutoComElem = null;
var AutoComElemVal = null;
var AutoComElemLookUp = null;
var AutoComElemValLookUp = null;
var TimerId = null;
var TimerIdLookUp = null;
var LDinnerDaysDiffer = null;

$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("Quotation") != -1) {
        $("#SideHeaderTabOperation").removeClass("ActiveTab");
        $("#SideHeaderTabQuotation").addClass("ActiveTab");
       // $("#LoadingDiv").show();
        $.ajax({
            url: urls["LoadQuotationDetails"],
            data: { 'QuotaId': $("#QuotationID").val() },
            type: 'POST',
            success: function (data) {
                $("#QuotaDetailsDiv").html(data);
            },
            error: function (xhr) {
                //  alert('Error: ' + xhr.statusText);
            },
            complete: function () {
                //   $("#LoadingDiv").hide();
                InitTabs($("#QuotaID").val());
                InitCalendars();
                $("#QuotaToNum").val($("#QuotaID").val());
                if (path.indexOf("Quotation/Quotation") != -1) {
                    $("#QuotaToNum").attr("max", parseInt($("#QuotaID").val()));
                }
                if ($("#MainQuotaMessage").length > 0) {
                    if ($("#MainQuotaMessage").val() != "" || $("#MainQuotaMessage").val() != null) {
                        $("#QuotaLockUnLockButton").attr('disabled', 'disabled');
                        jAlert($("#MainQuotaMessage").val(), "Warning!");
                    }
                }
            }
        });
    }
});

// LookUp text 
$(document).on('input', '#Lookup', function () {
    if (TimerIdLookUp == null) {
        AutoComElemLookUp = $(this).attr('id');
        AutoComElemValLookUp = $("#" + AutoComElemLookUp).val();
        TimerIdLookUp = setInterval(function () {

            var keyword = $("#" + AutoComElemLookUp).val();
            if (keyword == AutoComElemValLookUp) {

                var position = $("#" + AutoComElemLookUp).offset();
                position.top = position.top + $("#" + AutoComElemLookUp).height() + 5;

                var byref;
                if ($("#QuotaNum").is(":checked"))
                    byref = "ID";
                if ($("#Ref").is(":checked"))
                    byref = "Ref";
                if ($("#Agency").is(":checked"))
                    byref = "Agency";
                if ($("#Cust").is(":checked"))
                    byref = "Cust";
                $.ajax({
                    url: urls["LoadQuotaLookupData"],
                    data: "ByRef=" + byref + "&Keyword=" + $("#Lookup").val(),
                    type: 'POST',
                    success: function (data) {
                        $("#QuotaLookupDiv").html(data);
                        var width = $("#" + AutoComElemLookUp).css("width");
                        $("#QuotaLookupDiv").css("width", width);
                        $("#QuotaLookupDiv").show();
                        $("#QuotaLookupDiv").offset(position);
                    },
                    error: function (xhr) {
                        //  alert('Error: ' + xhr.statusText);
                    },
                    complete: function () {
                        clearInterval(TimerIdLookUp);
                        TimerIdLookUp = null;
                    }
                });
            }
            else
                AutoComElemValLookUp = keyword;
        }, 600);
    }
});


// lookup radio buttons
$(document).on('click', '#QuotaNum', function () {
    if ($("#QuotaNum").is(":checked"))
    {
        $("#Ref").prop("checked", false);
        $("#Agency").prop("checked", false);
        $("#Cust").prop("checked", false);
    }
});
$(document).on('click', '#Ref', function () {
    if ($("#Ref").is(":checked")) {
        $("#QuotaNum").prop("checked", false);
        $("#Agency").prop("checked", false);
        $("#Cust").prop("checked", false);
    }
});
$(document).on('click', '#Agency', function () {
    if ($("#Agency").is(":checked")) {
        $("#QuotaNum").prop("checked", false);
        $("#Ref").prop("checked", false);
        $("#Cust").prop("checked", false);
    }
});
$(document).on('click', '#Cust', function () {
    if ($("#Cust").is(":checked")) {
        $("#QuotaNum").prop("checked", false);
        $("#Ref").prop("checked", false);
        $("#Agency").prop("checked", false);
    }
});

function LookUpRowClick(QuotaId) {
    $("#Lookup").val(QuotaId);
    $("#QuotaLookupDiv").hide();
    $('#QuotaGoButton').click();
}

// hide lookup div when div selected
$(document).on('click', '#QuotaLookupDiv', function () {
    $("#QuotaLookupDiv").hide();
});

function QuotaGo()
{
   // $("#LoadingDiv").show();
    // quota details load
    $.ajax({
        url: urls["LoadQuotationDetails"],
        data: { 'QuotaId': $("#Lookup").val() },
        type: 'POST',
        success: function (data) {
            $("#QuotaDetailsDiv").html(data);
            // $("#LoadingDiv").hide();
           // $("#LoadingDiv").css('display', 'none');
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
            InitTabs($("#QuotaID").val());
            InitCalendars();
            $("#QuotaToNum").val($("#QuotaID").val());
            $("#Lookup").val("");
        }
    });
}

// Quota details Save button click
$(document).on('click', '#SaveBtn', function () {
    if ($("#QuotaConfirmed").is(":checked") && $("#QuotaConfirmed").is(":disabled"))
    {
        jAlert("You can't make any changes into confirmed quotation.", 'Error!');
        return;
    }
    CheckTabUnsavedData();
    if (ValidateQuotaDetails()) {
        // are you shure color box
        var QuotationDetailViewModel = {
            QuotaID: $("#QuotaID").val(),
            QuotaConfirmed: $("#QuotaConfirmed").is(":checked") ? true : false,
            GroupIsGir: $("#GroupIsGir").is(":checked") ? true : false,
            SelQuotaCountry: $("#SelQuotaCountry").val(),
            NoOfFlights: $("#NoOfFlights").val(),
            SelectedRegion: $("#SelectedRegion").val(),
            QuotaCode: $("#QuotaCode").val(),
            SelectedCustomerId: $("#SelectedCustomerId").val(),
            SelectedSeason: $("#SelectedSeason").val(),
            QuotaName: $("#QuotaName").val(),
            QuotaNote: $("#QuotaNote").val(),
            SelectedEmployeeId: $("#SelectedEmployeeId").val(),
            NoNights: $("#NoNights").val(),
            ArrivalDate: $("#ArrivalDate").val(),
            SelectedArrivalCity: $("#SelectedArrivalCity").val(),
            QuotaDate: $("#QuotaDate").val(),
            NoOfMeals: $("#NoOfMeals").val(),
            DepartureDate: $("#DepartureDate").val(),
            SelectedDepartureCity: $("#SelectedDepartureCity").val(),
            LastUpDate: $("#LastUpDate").val(),
            MaxNoOfPax: $("#MaxNoOfPax").val(),
            MinNoOfPax: $("#MinNoOfPax").val(),
            IncNoOfPax: $("#IncNoOfPax").val(),
            HFreeRoom: $("#HFreeRoom").val(),
            HForPaid: $("#HForPaid").val(),
            SelectedFreeCalcType: $("#SelectedFreeCalcType").val(),
            profit: $("#profit").val(),
            OFreeService: $("#OFreeService").val(),
            OForPaid: $("#OForPaid").val(),
            Proposal: $("#Proposal").val(),
        };
        var DTO = JSON.stringify(QuotationDetailViewModel);

        $.ajax({
            url: urls["SaveQuotaDetailsData"],
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: DTO,
            success: function (data) {
                $("#QuotaDetailsDiv").html(data);
                if($("#QuotaDetailMessage").val() != "")
                    jAlert($("#QuotaDetailMessage").val(), 'Error!');
            },
            error: function (xhr) {
                //   alert('Error: ' + xhr.statusText);
            },
            complete: function () {
                //  $("#LoadingDiv").hide();
                InitCalendars();
                InitTabs($("#QuotaIden").val());
                $("#QuotaToNum").val($("#QuotaIden").val());
            }
        });
    }
});


// Quota details SaveAs button click
$(document).on('click', '#SaveAsBtn', function () {
    // $("#QuotaDetailsDiv").html("");
    CheckTabUnsavedData();
    if (ValidateQuotaDetails()) {
        $.ajax({
            url: urls["SaveAsQuotaDetailsData"],
            data: { 'QuotaId': $("#QuotaID").val() },
            type: 'POST',
            success: function (data) {
                $("#QuotaDetailsDiv").html(data); 
            },
            error: function (xhr) {
                //  alert('Error: ' + xhr.statusText);
            },
            complete: function () {
                InitTabs($("#QuotaIden").val());
                InitCalendars();
                $("#QuotaToNum").val($("#QuotaIden").val());
                jAlert($("#QuotaDetailMessage").val(), 'Info!');
            }
        });
    }
});

// Quota UnLock button click
$(document).on('click', '#UnLock', function () {
    $.ajax({
        url: urls["UnLockQuotation"],
        //data: { },
        type: 'POST',
        success: function (data) {
            $("#QuotaDetailsDiv").html(data);

            // $("#LoadingDiv").hide();
            // $("#LoadingDiv").css('display', 'none');
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
            InitTabs($("#QuotaID").val());
            InitCalendars();
            $("#QuotaToNum").val($("#QuotaID").val());
        }
    });
});
// Quota details New button click
$(document).on('click', '#NewBtn', function () {
    $.ajax({
        url: urls["NewQuotationDetails"],
        //data: { },
        type: 'POST',
        success: function (data) {
            $("#QuotaDetailsDiv").html(data);
           
            // $("#LoadingDiv").hide();
           // $("#LoadingDiv").css('display', 'none');
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
            InitTabs($("#QuotaID").val());
            InitCalendars();
            $("#QuotaToNum").val($("#QuotaID").val());
        }
    });
});

function ValidateQuotaDetails()
{
    var val = true;
    if($("#SelectedCustomerId").val() == "")
    {
        jAlert("Please fill Customer.", 'Attention!');
        val = false;
    }
    else if ($("#SelectedRegion").val() == "") {
        jAlert("Please fill Region.", 'Attention!');
        val = false;
    }
    else if ($("#SelectedEmployeeId").val() == "") {
        jAlert("Please fill Employee.", 'Attention!');
        val = false;
    }
    else if (!Date.parse($("#ArrivalDate").val()) && $("#ArrivalDate").val() != "") {
        jAlert("Please Input Valid Arrival Date.", 'Attention!');
        val = false;
    }
    else if ($("#QuotaConfirmed").is(":checked") && $("#ArrivalDate").val() == "") {
        jAlert("Please fill Arrival Date.", 'Attention!');
        val = false;
    }
    if ($("#QuotaConfirmed").is(":checked") && val)
    {
        val = NightsValidation(true);
        val = MealsValidation(true);
    }
    return val;
}

function CheckTabUnsavedData()
{
    if ($("#HotelTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#HotelTabUpdate").click();
    }
    if ($("#LunchTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#LunchTabUpdate").click();
    }
    if ($("#EntranceTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#EntranceTabUpdate").click();
    }
    if ($("#MiscTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#MiscTabUpdate").click();
    }
    if ($("#BusTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#BusTabUpdate").click();
    }
    if ($("#GuideTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#GuideTabUpdate").click();
    }    
}

function ValidateQuotaNewGirGroup() {
    var val = true;
    if ($("#AddGirGroupCode").val() == "") {
        jAlert("Please fill Group Code.", 'Attention!');
        val = false;
    }
    else if ($.isNumeric($("#AddGirGroupCode").val())) {
        jAlert("Group code can not contains only numbers", "Error");
        val = false;
    }
    if ($("#AddGirGroupName").val() == "" && val) {
        jAlert("Please fill Group Name.", 'Attention!');
        val = false;
    }
    if ($("#AddGirArrivalDate").val() == "" && val) {
        jAlert("Please fill Group Arrival Date.", 'Attention!');
        val = false;
    }
    if (!Date.parse($("#AddGirArrivalDate").val()) && val) {
        jAlert("Please Input Valid Arrival Date.", 'Attention!');
        val = false;
    }
    if ($("#AddGirNoNights").val() == "" && val) {
        jAlert("Please fill Night.", 'Attention!');
        val = false;
    }
    if ($("#AddGirPax").val() == "" && val) {
        jAlert("Please fill Pax.", 'Attention!');
        val = false;
    }
    if ($("#AddGirRoom").val() == "" && val) {
        jAlert("Please fill Room.", 'Attention!');
        val = false;
    }
    return val;
}
function ValidateQuotaNewGirGroupFromServer() {
    var valid = true;
    $.ajax({
        url: urls["QuotationCreateGroupValidation"],
        data: { 'ArrivalDate': $("#AddGirArrivalDate").val() },
        type: 'POST',
        async: false,
        success: function (data) {
            if (!data) {
                jAlert("Group arrival date can not be earlier than current date.", 'Warning!');
            }
            valid = data;
        },
    });
    return valid;
}
function ValidateQuotaGirGroup() {
    var val = true;
    jQuery('.GirGroupCode').each(function (currentElement, index) {
        if ($(this).val() == "") {
            jAlert("Please fill Group Code.", 'Attention!');
            val = false;
        }
    });
    if (val) {
        jQuery('.GirGroupName').each(function (currentElement, index) {
            if ($(this).val() == "") {
                jAlert("Please fill Group Name.", 'Attention!');
                val = false;
            }
        });
    }
    if (val) {
        jQuery('.GirArrivalDate').each(function (currentElement, index) {
            if ($(this).val() == "") {
                jAlert("Please fill Group Arrival Date.", 'Attention!');
                val = false;
            }
            if (!Date.parse($(this).val()) && val) {
                jAlert("Please Input Valid Arrival Date.", 'Attention!');
                val = false;
            }
        });
    }
    if (val) {
        jQuery('.GirPax').each(function (currentElement, index) {
            if ($(this).val() == "") {
                jAlert("Please fill Pax.", 'Attention!');
                val = false;
            }
        });
    }
    if (val) {
        jQuery('.GirRoom').each(function (currentElement, index) {
            if ($(this).val() == "") {
                jAlert("Please fill Room.", 'Attention!');
                val = false;
            }
        });
    }
    return val;
}
function ValidateQuotaNewGirGroupCustomer() {
    var val = true;
    if ($("#AddInvCustomer").val() == "") {
        jAlert("Please fill Customer.", 'Attention!');
        val = false;
    }
    return val;
}
//function ValidateQuotaGirGroupCustomer() {
//    var val = true;
//    jQuery('.GirGroupInvCustomer').each(function (currentElement, index) {
//        if ($(this).val() == "") {
//            jAlert("Please fill Customer.", 'Attention!');
//            val = false;
//        }
//    });
//    return val;
//}
$(document).on('keydown', '.QuotaOnlyCurrency', function (event) {
    if (event.keyCode == 67 || event.keyCode == 65 || event.keyCode == 85 ||
          event.keyCode == 83) {
    }
    else {
        event.preventDefault();
    }
});

function InitTabs(QuotaId) {
    var HotelUpd = false;
    var MealUpd = false;
    // hotel tab load
    $.ajax({
        url: urls["LoadQuotationHotelTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabHotels").html(data);
        },
        error: function (xhr) {
              alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            $("#Tabs").show();
            HotelUpd = true;
            if (HotelUpd == true && MealUpd == true) {
                $("#CalculateCostBtn").click();
            }
        }
    });

    // lunch dinner tab load
    $.ajax({
        url: urls["LoadQuotationLunchDinnerTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabLunchDinner").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            MealUpd = true;
            if(HotelUpd == true && MealUpd == true) {
                $("#CalculateCostBtn").click();
            }
        }
    });
    // entrance tab load
    $.ajax({
        url: urls["LoadQuotationEntranceTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabEntrance").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
        }
    });
    // Misc tab load
    $.ajax({
        url: urls["LoadQuotationMiscTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabGrpMisc").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
        }
    });
    // Bus tab load
    $.ajax({
        url: urls["LoadQuotationBusTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabBus").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
            BindBusServiceDrop();
        }
    });

    // Guide tab load
    $.ajax({
        url: urls["LoadQuotationGuideTab"],
        data: { 'QuotaId': QuotaId },
        type: 'POST',
        success: function (data) {
            $("#tabGuide").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
            BindGuideServiceDrop();
        }
    });

    // Cost/price tab load
    $.ajax({
        url: urls["LoadQuotationCostPriceTab"],
        
        data: "QuotaId=" + QuotaId + "&FreeCalc=" + $("#SelectedFreeCalcType").val(),
        type: 'POST',
        success: function (data) {
            $("#tabCost").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            // $("#LoadingDiv").hide();
        }
    });

}

// Cost/Price
// calculate button click
$(document).on('click', '#CalculateCostBtn', function () {
    var ValidateAns = true;
    ValidateAns = NightsValidation(false);
    if (ValidateAns == true)
        ValidateAns = MealsValidation(false);
    if (ValidateAns == false)
    {
        $("#tabhrefCost").attr('style', 'background-color: red !important');
    }
    else
    {
        $("#tabhrefCost").attr('style', 'background-color: green !important');
    }
 
    if ($("#profit").val() >= 1) {
        jAlert("will not calculate, profit should be less than 1", 'Attention!');
    }
    else {
        $("#CostPriceFreeCalc").val($("#SelectedFreeCalcType").val());
        $("#CostPriceQuotaID").val($("#QuotaID").val());
        $("#QuotaCostPriceGridForm").submit();
    }
});

// Tabs Line
function HotelNewLine() {
    if ($("#HotelTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#QuotaHotelIsNewLine").val("True");
        $("#QuotaHotelGridForm").submit();
    }
    else {
        $.ajax({
            url: urls["NewLineQuotationHotelTab"],
            data: { 'QuotaId': $("#QuotaIden").val() },
            type: 'POST',
            success: function (data) {
                $("#tabHotels").html(data);
            },
            error: function (xhr) {
                //  alert('Error: ' + xhr.statusText);
            },
            complete: function () {
                //  $("#LoadingDiv").hide();
            }
        });
    }
}

function InsertLineHotelGrid() {
    if ($("#HotelTabUpdate").hasClass("QuotaDetDataChanged")) {
        $("#QuotaHotelIsInsert").val("True");
        $("#QuotaHotelInsertRow").val($("#HotelInsertLine").val());
        $("#QuotaHotelGridForm").submit();
    }
    else {
        $.ajax({
            url: urls["InsertLineQuotationHotelTab"],
            data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#HotelInsertLine").val(),
            type: 'POST',
            success: function (data) {
                $("#tabHotels").html(data);
            },
            error: function (xhr) {
                //  alert('Error: ' + xhr.statusText);
            },
            complete: function () {
                //  $("#LoadingDiv").hide();
            }
        });
    }
}

function InsertLineLunchDinnerGrid() {
    if ($("#LunchTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaLunchDinnerGridForm").submit();
    $.ajax({
        url: urls["InsertLineQuotationLunchDinnerTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#LunchDinnerInsertLine").val(),
        type: 'POST',
        success: function (data) {
            $("#tabLunchDinner").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
          //  $("#LoadingDiv").hide();
        }
    });
}

function LunchDinnerNewLine() {
    if ($("#LunchTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaLunchDinnerGridForm").submit();
    $.ajax({
        url: urls["NewLineQuotationLunchDinnerTab"],
        data: { 'QuotaId': $("#QuotaIden").val() },
        type: 'POST',
        success: function (data) {
            $("#tabLunchDinner").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
          //  $("#LoadingDiv").hide();
        }
    });
}

function InsertLineEntranceGrid() {
    if ($("#EntranceTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaEntranceGridForm").submit();
    $.ajax({
        url: urls["InsertLineQuotationEntranceTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#EntranceInsertLine").val(),
        type: 'POST',
        success: function (data) {
            $("#tabEntrance").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
          //  $("#LoadingDiv").hide();
        }
    });
}

function EntranceNewLine() {
    if ($("#EntranceTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaEntranceGridForm").submit();
    $.ajax({
        url: urls["NewLineQuotationEntranceTab"],
        data: { 'QuotaId': $("#QuotaIden").val() },
        type: 'POST',
        success: function (data) {
            $("#tabEntrance").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
         //   $("#LoadingDiv").hide();
        }
    });
}

function InsertLineMiscGrid() {
    if ($("#MiscTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaMiscGridForm").submit();
    $.ajax({
        url: urls["InsertLineQuotationMiscTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#MiscInsertLine").val(),
        type: 'POST',
        success: function (data) {
            $("#tabGrpMisc").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
         //   $("#LoadingDiv").hide();
        }
    });
}

function MiscNewLine() {
    if ($("#MiscTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaMiscGridForm").submit();
    $.ajax({
        url: urls["NewLineQuotationMiscTab"],
        data: { 'QuotaId': $("#QuotaIden").val() },
        type: 'POST',
        success: function (data) {
            $("#tabGrpMisc").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
          //  $("#LoadingDiv").hide();
        }
    });
}

function InsertLineBusGrid() {
    if ($("#BusTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaBusGridForm").submit();
    $.ajax({
        url: urls["InsertLineQuotationBusTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#BusInsertLine").val(),
        type: 'POST',
        success: function (data) {
            $("#tabBus").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            BindBusServiceDrop();
        }
    });
}

function BusNewLine() {
    if ($("#BusTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaBusGridForm").submit();
    $.ajax({
        url: urls["NewLineQuotationBusTab"],
        data: { 'QuotaId': $("#QuotaIden").val() },
        type: 'POST',
        success: function (data) {
            $("#tabBus").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            BindBusServiceDrop();
        }
    });
}

function InsertLineGuideGrid() {
    if ($("#GuideTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaGuideGridForm").submit();
    $.ajax({
        url: urls["InsertLineQuotationGuideTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNum=" + $("#GuideInsertLine").val(),
        type: 'POST',
        success: function (data) {
            $("#tabGuide").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            BindGuideServiceDrop();
        }
    });
}

function GuideNewLine() {
    if ($("#GuideTabUpdate").hasClass("QuotaDetDataChanged"))
        $("#QuotaGuideGridForm").submit();
    $.ajax({
        url: urls["NewLineQuotationGuideTab"],
        data: { 'QuotaId': $("#QuotaIden").val() },
        type: 'POST',
        success: function (data) {
            $("#tabGuide").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            BindGuideServiceDrop();
        }
    });
}


// Delete
function RemoveHotel(ItmID, LineNo) {
    if ($("#HotelTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaHotelGridForm").submit();
                RemoveHotelAjax(ItmID, LineNo);
            }
            else
            {
                RemoveHotelAjax(ItmID, LineNo);
            }
        });
    }
    else
    {
        RemoveHotelAjax(ItmID, LineNo);
    }
    
}
function RemoveHotelAjax(ItmID, LineNo)
{
    $.ajax({
        url: urls["RemoveQuotationHotelTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabHotels").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
        }
    });
}
function RemoveLunchDinner(ItmID, LineNo) {
    if ($("#LunchTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaLunchDinnerGridForm").submit();
                RemoveLunchDinnerAjax(ItmID, LineNo);
            }
            else {
                RemoveLunchDinnerAjax(ItmID, LineNo);
            }
        });
    }
    else {
        RemoveLunchDinnerAjax(ItmID, LineNo);
    }
}   
function RemoveLunchDinnerAjax(ItmID, LineNo) {
    $.ajax({
        url: urls["RemoveQuotationLunchDinnerTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabLunchDinner").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //  $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
        }
    });
}
function RemoveEntrance(ItmID, LineNo) {
    if ($("#EntranceTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaEntranceGridForm").submit();
                RemoveEntranceAjax(ItmID, LineNo);
            }
            else {
                RemoveEntranceAjax(ItmID, LineNo);
            }
        });
    }
    else {
        RemoveEntranceAjax(ItmID, LineNo);
    }
}
function RemoveEntranceAjax(ItmID, LineNo) {
    $.ajax({
        url: urls["RemoveQuotationEntranceTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabEntrance").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
        }
    });
}

function RemoveMisc(ItmID, LineNo) {
    if ($("#MiscTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaMiscGridForm").submit();
                RemoveMiscAjax(ItmID, LineNo);
            }
            else {
                RemoveMiscAjax(ItmID, LineNo);
            }
        });
    }
    else {
        RemoveMiscAjax(ItmID, LineNo);
    }
}
function RemoveMiscAjax(ItmID, LineNo) {
    $.ajax({
        url: urls["RemoveQuotationMiscTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabGrpMisc").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
        }
    });
}
function RemoveBus(ItmID, LineNo) {
    if ($("#BusTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaBusGridForm").submit();
                RemoveBusAjax(ItmID, LineNo);
            }
            else {
                RemoveBusAjax(ItmID, LineNo);
            }
        });
    }
    else {
        RemoveBusAjax(ItmID, LineNo);
    }
}
function RemoveBusAjax(ItmID, LineNo) {
    $.ajax({
        url: urls["RemoveQuotationBusTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabBus").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
            BindBusServiceDrop();
        }
    });
}
function RemoveGuide(ItmID, LineNo) {
    if ($("#GuideTabUpdate").hasClass("QuotaDetDataChanged")) {
        jConfirm('There are unsaved data, do you want save and continue?', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#QuotaGuideGridForm").submit();
                RemoveGuideAjax(ItmID, LineNo);
            }
            else {
                RemoveGuideAjax(ItmID, LineNo);
            }
        });
    }
    else {
        RemoveGuideAjax(ItmID, LineNo);
    }
}
function RemoveGuideAjax(ItmID, LineNo) {
    $.ajax({
        url: urls["RemoveQuotationGuideTab"],
        data: "ItmID=" + ItmID + "&QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo,
        type: 'POST',
        success: function (data) {
            $("#tabGuide").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
            //   $("#LoadingDiv").hide();
            $("#CalculateCostBtn").click();
            BindGuideServiceDrop();
        }
    });
}
function RemoveCostPrice(LineNo) {
    $.ajax({
        url: urls["RemoveQuotationCostPriceTab"],
        data: "QuotaId=" + $("#QuotaIden").val() + "&LineNo=" + LineNo + "&FreeCalc=" + $("#SelectedFreeCalcType").val(),
        type: 'POST',
        success: function (data) {
            $("#tabCost").html(data);
        },
        error: function (xhr) {
            //  alert('Error: ' + xhr.statusText);
        },
        complete: function () {
          //  $("#LoadingDiv").hide();
        }
    });
}

function InitCalendars()
{
    $("#ArrivalDate").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'D, dd/M/y',
        onClose: function (selectedDate) {
            $("#DepartureDate").datepicker("option", "minDate", selectedDate);
        }
    });
    // check for Fri Sat
    var str = $("#ArrivalDate").val();
    if (str != null && (str.indexOf("Fri") != -1 || str.indexOf("Sat") != -1))
        $("#ArrivalDate").addClass("QuotaDatesFriSat");

    $("#QuotaDate").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'D, dd/M/y',
    });
    $("#LastUpDate").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'D, dd/M/y',
    });
}
// Arrival date changes
$(document).on('change', '#ArrivalDate', function () {
    var str = $("#ArrivalDate").val();
    if (str != null && (str.indexOf("Fri") != -1 || str.indexOf("Sat") != -1))
        $("#ArrivalDate").addClass("QuotaDatesFriSat");
    else
        $("#ArrivalDate").removeClass("QuotaDatesFriSat");
});

// reports
$(document).on('click', '#ReportBtn', function () {
   // var Id = $("#QuotaIden").val();
    window.open("../Report/QuotationReport?Id=" + $("#QuotaIden").val() + "&FreeCalc=" + $("#SelectedFreeCalcType").val() + "&Small=" + $("#ReportSmallChb").is(":checked"));
    
});

// upload proposal

$(document).on('change', '#ProposalFile', function () {
    // check if all saved
    if ($("#SaveBtn").hasClass("QuotaDetDataChanged")) {
        $("#SaveBtn").click();
    }
    if ($('#ProposalFile').attr('value', $('#attachment').val()) != null)
        $('#UploadProposal').click();
});

$(document).on('focus', '.QuotaTextBx', function () {
    if (!PrevValChange) {
        PrevVal = $(this).val();
        PrevValChange = true;
    }
});

$(document).on('focus', '.PopUpQuotaTextBx', function () {
    if (!PopUpPrevValChange) {
        PopUpPrevVal = $(this).val();
        PopUpPrevValChange = true;
    }
});

// Money Validations

// Breakfast validation over 25
$(document).on('change', '.Brfast', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 25)
    {
        jConfirm('The value entered is over 25. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// Luggage validation over 10
$(document).on('change', '.Lugg', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 10) {
        jConfirm('The value entered is over 10. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// Tax validation over 25%
$(document).on('change', '.Tax', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 25) {
        jConfirm('The value entered is over 25%. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// acc tax validation over 5
$(document).on('change', '.Occtax', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 5) {
        jConfirm('The value entered is over 5. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// room validation over 300, less 40
$(document).on('change', '.room', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 300) {
        jConfirm('The value entered is over 300. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 40) {
        jConfirm('The value entered is less 40. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// Lunch cost validation over 60, less 10
$(document).on('change', '.LCost', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 60) {
        jConfirm('The value entered is over 60. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 10 && itm.val() > 0) {
        jConfirm('The value entered is less 10. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
   // MealsValidation();
});

// Dinner cost validation over 60, less 10
$(document).on('change', '.DCost', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 60) {
        jConfirm('The value entered is over 60. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 10 && itm.val() > 0) {
        jConfirm('The value entered is less 10. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
   // MealsValidation();
});

// Entrance PP cost validation over 100
$(document).on('change', '.PPCost', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 100) {
        jConfirm('The value entered is over 100. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});
// Bus Rate validation over 1500, less 250
$(document).on('change', '.BusRate', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 1500) {
        jConfirm('The value entered is over 1500. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 250) {
        jConfirm('The value entered is less 250. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});
// Guide Rate validation over 350, less 120
$(document).on('change', '.GuideRate', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 350) {
        jConfirm('The value entered is over 350. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 120) {
        jConfirm('The value entered is less 120. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});


// profit validation
$(document).on('change', '#profit', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() > 1) {
        jConfirm('The value entered is over 1. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
    if (itm.val() < 0.75) {
        jConfirm('The value entered is less 0.75. Do you want to continue ?', 'Warning!', function (retVal) {
            if (retVal == false) {
                itm.val(PrevVal);
            }
        });
    }
});

// Day Validation
$(document).on('change', '.QuotaDay', function () {
    PrevValChange = false;
    var itm = $(this);
    var night = parseInt($("#NoNights").val());
    if (parseInt(itm.val()) > night + 1) {
        jAlert("The # of Days can't be more than # of Nights + 1", 'Attention!');
        itm.val(PrevVal);
    }
    else {
        if ($("#ArrivalDate").val().length > 0) {
            var CurDate = new Date($("#ArrivalDate").val());
            CurDate.setDate(CurDate.getDate() + parseInt(itm.val()) - 1);
            var ShowDateStr = $.datepicker.formatDate('D, dd/M/y', CurDate);
            var DateLbl = itm.parent().next().children().first();
            if (CurDate.getDay() == 5 || CurDate.getDay() == 6)
                DateLbl.addClass("QuotaDatesFriSat");
            else
                DateLbl.removeClass("QuotaDatesFriSat");
            DateLbl.html(ShowDateStr);
        } 
    }
});


// Nights Validation
$(document).on('change', '#NoNights', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Nights can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }
});
$(document).on('change', '.HotelNights', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Nights can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }

    // calc nights
    var NightSum = 0;
    $(".HotelNights").each(function (index, elem) {
        NightSum += parseInt($(elem).val());
    });
    $("#NightSum").val(NightSum);
});
$(document).on('change', '.GirNights', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Nights can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }
});
$(document).on('change', '.PopUpGirNights', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Nights can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }
});
$(document).on('change', '.PopUpGirPax', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Pax can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }
});
$(document).on('change', '.PopUpGirRoom', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() == 0) {
        jAlert("The number of Room can't be 0.", 'Attention!');
        itm.val(PrevVal);
    }
});

// Meals
$(document).on('change', '.MealCost', function () {
    // calc meals
    var MealsLSum = 0;
    var MealsDSum = 0;
    $(".LCost").each(function (index, elem) {
        if ($(elem).val() > 0)
            MealsLSum++;
    });
    $(".DCost").each(function (index, elem) {
        if ($(elem).val() > 0)
            MealsDSum++;
    });
    $("#LunchSum").val(MealsLSum);
    $("#DinnerSum").val(MealsDSum);
    $("#LunchDinnerSum").val(MealsLSum + MealsDSum);
});

// Currency Validation
$(document).on('change', '.CurrencyHotel', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

$(document).on('change', '.CurrencyEntrance', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

$(document).on('change', '.CurrencyMisc', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

$(document).on('change', '.CurrencyLunchDinner', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

$(document).on('change', '.CurrencyBus', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

$(document).on('change', '.CurrencyGuide', function () {
    PrevValChange = false;
    var itm = $(this);
    if (itm.val() != "US" || itm.val() != "CA") {
        jAlert("Wrong currency inserted.", 'Attention!');
        itm.val(PrevVal);
    }
});

function NightsValidation(PrintMessage) {
    var NightSum = 0;
    $(".HotelNights").each(function (index, elem) {
        NightSum += parseInt($(elem).val());
    });
    if (NightSum != $("#NoNights").val()) {
        if (PrintMessage == true)
            jAlert('The number of Nights you entered is different than what you determined.', 'Attention!');
        return false;
    }
    return true;
}
function ValidateHotelVendorIDS(PrintMessage) {
    var VendorIDs = [];
    var valid = true;
    $(".HotelMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            VendorIDs.push($(elem).parent().parent().find(".HotelID").val());
    });
    $(VendorIDs).each(function (index, elem) {
        if (elem == null || elem == "" || elem == 0) {
            if (PrintMessage == true)
                jAlert('Please choose hotel from autocomplete div.', 'Error!');
            valid = false;
            return false;
        }
    });
    return valid;
}
function ValidateLunchDinnerVendorIDS(PrintMessage) {
    var VendorIDs = [];
    var valid = true;
    $(".LunchMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            VendorIDs.push($(elem).parent().parent().find(".LunchID").val());
    });
    $(".DinnerMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            VendorIDs.push($(elem).parent().parent().find(".DinnerID").val());
    });
    $(VendorIDs).each(function (index, elem) {
        if (elem == null || elem == "" || elem == 0) {
            if (PrintMessage == true)
                jAlert('Please choose hotel lunch dinner autocomplete div.', 'Error!');
            valid = false;
            return false;
        }
    });
    return valid;
}
function ValidateEntranceVendorIDS(PrintMessage) {
    var VendorIDs = [];
    var valid = true;
    $(".EntranceMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            VendorIDs.push($(elem).parent().parent().find(".EntranceID").val());
    });
    $(VendorIDs).each(function (index, elem) {
        if (elem == null || elem == "" || elem == 0) {
            if (PrintMessage == true)
                jAlert('Please choose entrance from autocomplete div.', 'Error!');
            valid = false;
            return false;
        }
    });
    return valid;
}
function ValidateBusVendorIDS(PrintMessage) {
    var VendorIDs = [];
    var valid = true;
    $(".BusMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            VendorIDs.push($(elem).parent().parent().find(".BusID").val());
    });
    $(VendorIDs).each(function (index, elem) {
        if (elem == null || elem == "" || elem == 0) {
            if (PrintMessage == true)
                jAlert('Please choose bus from autocomplete div.', 'Error!');
            valid = false;
            return false;
        }
    });
    return valid;
}
function ValidateGuideIDS(PrintMessage) {
    var GuideIDs = [];
    var valid = true;
    $(".GuideMFlag").each(function (index, elem) {
        if (!($(elem).is(":checked")))
            GuideIDs.push($(elem).parent().parent().find(".GuideID").val());
    });
    $(GuideIDs).each(function (index, elem) {
        if (elem == null || elem == "" || elem == 0) {
            if (PrintMessage == true)
                jAlert('Please choose guide from autocomplete div.', 'Error!');
            valid = false;
            return false;
        }
    });
    return valid;
}
// Meals Validation
function MealsValidation(PrintMessage) {
    var MealsSum = 0;
    $(".LCost").each(function (index, elem) {
        if ($(elem).val() > 0)
            MealsSum ++;
    });
    $(".DCost").each(function (index, elem) {
        if ($(elem).val() > 0)
            MealsSum++;
    });
    if ($(".LCost").length && MealsSum != $("#NoOfMeals").val()) {
        if (PrintMessage == true)
           jAlert('The number of Meals you entered is different than what you determined.', 'Attention!');
        return false;
    }
    return true;
}

 //Day, Number of Days validation
 $(document).on('change', '.DayCls', function () {
     PrevValChange = false;
     var itm = $(this);
     if (itm.val() == 0) {
         jAlert("The number of Days can't be 0.", 'Attention!');
         itm.val(PrevVal);
     }
});

 // Money textboxes format 
 $(document).on('change', '.QuotaMoneyTxb', function () {
     var val = parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2);
     $(this).val(val);
 });
// Quota Details Controls chnaged 
 $(document).on('change', '.QuotaDetControls', function () {
     if ($("#SaveBtn").length) {
         $("#SaveBtn").addClass("QuotaDetDataChanged");
     }
 });
// Quota Gir Group Controls chnaged 
 $(document).on('change', '.QuotaGirGrpControls', function () {
     if ($("#SaveGirGroupBtn").length > 0) {
         $("#SaveGirGroupBtn").addClass("QuotaDetDataChanged");
     }
 });
 // Quota Add Gir Group Controls chnaged 
 $(document).on('change', '.QuotaAddGirGrpControls', function () {
     $("#SaveNewGirGroupBtn").addClass("QuotaDetDataChanged");
 });
 // Quota Gir Group Customer Controls chnaged 
 $(document).on('change', '.QuotaGirGrpCustomerControls', function () {
     if ($("#SaveGirInvoiceBtn").length > 0) {
         $("#SaveGirInvoiceBtn").addClass("QuotaDetDataChanged");
     }
 });
// Quota Add Gir Group Customer Controls chnaged 
 $(document).on('change', '.QuotaAddGirGrpCustomerControls', function () {
     $("#SaveNewGirGroupCustomerBtn").addClass("QuotaDetDataChanged");
 });
 // Hotel tabs Details chnaged 
 $(document).on('change', '.HotelDetTab', function () {
     $("#HotelTabUpdate").addClass("QuotaDetDataChanged");
 });

 // Lunch dinner tabs Details chnaged 
 $(document).on('change', '.LunchDetTab', function () {
     $("#LunchTabUpdate").addClass("QuotaDetDataChanged");
 });

 // Entrance tabs Details chnaged 
 $(document).on('change', '.EntranceDetTab', function () {
     $("#EntranceTabUpdate").addClass("QuotaDetDataChanged");
 });

 // Misc tabs Details chnaged 
 $(document).on('change', '.MiscDetTab', function () {
     $("#MiscTabUpdate").addClass("QuotaDetDataChanged");
 });

 // Bus tabs Details chnaged 
 $(document).on('change', '.BusDetTab', function () {
     $("#BusTabUpdate").addClass("QuotaDetDataChanged");
 });

 // Guide tabs Details chnaged 
 $(document).on('change', '.GuideDetTab', function () {
     $("#GuideTabUpdate").addClass("QuotaDetDataChanged");
 });
 // Cost Price tabs Details chnaged 
 $(document).on('change', '.CostPriceDetTab', function () {
     $("#CalculateCostBtn").addClass("QuotaDetDataChanged");
 });

 // Hotel tab Update not allowed if Nights Validation not passed
 $(document).on('click', '#HotelTabUpdate', function () {
     if ((NightsValidation(true) == true) && (ValidateHotelVendorIDS(true) == true))
         $("#QuotaHotelGridForm").submit();
 });
 // Lunch Dinner tab Update not allowed if Meals Validation not passed
 $(document).on('click', '#LunchTabUpdate', function () {
     $(".QuotaLunchDinnerDay").each(function (index, elem) {
         $(".QuotaLunchDinnerDay").each(function (index1, elem1) {
             if (index1 > index && $(elem).val() == $(elem1).val()) {
                 jAlert("Day numbers should be differ.", 'Attention!');
                 return;
             }
         });
     });
     if (MealsValidation(true) == true && (ValidateLunchDinnerVendorIDS(true) == true))
         $("#QuotaLunchDinnerGridForm").submit();
 });
 $(document).on('click', '#EntranceTabUpdate', function () {
     if (ValidateEntranceVendorIDS(true) == true)
         $("#QuotaEntranceGridForm").submit();
 });
 $(document).on('click', '#BusTabUpdate', function () {
     if (ValidateBusVendorIDS(true) == true)
         $("#QuotaBusGridForm").submit();
 });
 $(document).on('click', '#GuideTabUpdate', function () {
     if (ValidateGuideIDS(true) == true)
         $("#QuotaGuideGridForm").submit();
 });


// Go to Quotation Record
 function QuotationGoTo()
 {
     if ($("#QuotaToNum").val()>0)
        window.location = '../Quotation/QuotationByRecord?RecordId=' + $("#QuotaToNum").val();
 }

// Advanced Search
 function AdvnacedSearch() {
     $.ajax({
         url: urls["QuotaAdvancedSearch"],
         type: 'GET',
         success: function (data) {
             $("#QuotaAdvancedSearch").html(data);
         },
         error: function (xhr) {
             //  alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             ShowAdvancedSearchPopUp();
         }
     });
 }
 function ShowAdvancedSearchPopUp()
 {
     $("#QuotaAdvancedSearch").show();
     $.colorbox({
         width: "1170px",
         height: "650px",
         inline: true,
         href: "#QuotaAdvancedSearch",
         onComplete: function () {
             // init calendars
             $("#QuotaDateFromAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#QuotaDateToAd").datepicker("option", "minDate", selectedDate);
                 }
             });
             $("#QuotaDateToAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#QuotaDateFromAd").datepicker("option", "maxDate", selectedDate);
                 }
             });
             $("#ArrivalDateFromAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#ArrivalDateToAd").datepicker("option", "minDate", selectedDate);
                 }
             });
             $("#ArrivalDateToAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#ArrivalDateFromAd").datepicker("option", "maxDate", selectedDate);
                 }
             });
             $("#LastUpdateFromAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#LastUpdateToAd").datepicker("option", "minDate", selectedDate);
                 }
             });
             $("#LastUpdateToAd").datepicker({
                 defaultDate: "+1w",
                 changeMonth: true,
                 changeYear: true,
                 numberOfMonths: 1,
                 dateFormat: 'D, dd/M/y',
                 beforeShow: function (input) {
                     $(input).css({
                         "position": "relative",
                         "z-index": 999999
                     });
                 },
                 onClose: function (selectedDate) {
                     $("#LastUpdateFromAd").datepicker("option", "maxDate", selectedDate);
                 }
             });
         },
         onClosed: function () {
             $("#QuotaAdvancedSearch").hide();
         }
     });
    
 }
 function AdvancedSearchBtnClick() {
     var QuotationAdvancedSearchViewModel = {
         SelectedAcceptedAd: $("#SelectedAcceptedAd").val(),
         SelectedQuotaTypeAd: $("#SelectedQuotaTypeAd").val(),
         SelectedRegionAd: $("#SelectedRegionAd").val(),
         QuotaCodeAd: $("#QuotaCodeAd").val(),
         SelectedCustomerIdAd: $("#SelectedCustomerIdAd").val(),
         SelectedSeasonAd: $("#SelectedSeasonAd").val(),
         QuotaNameAd: $("#QuotaNameAd").val(),
         SelectedEmployeeIdAd: $("#SelectedEmployeeIdAd").val(),
         NoNightsAd: $("#NoNightsAd").val(),
         ArrivalDateFromAd: $("#ArrivalDateFromAd").val(),
         ArrivalDateToAd: $("#ArrivalDateToAd").val(),
         SelectedArrivalCityAd: $("#SelectedArrivalCityAd").val(),
         QuotaDateFromAd: $("#QuotaDateFromAd").val(),
         QuotaDateToAd: $("#QuotaDateToAd").val(),
         LastUpdateFromAd: $("#LastUpdateFromAd").val(),
         LastUpdateToAd: $("#LastUpdateToAd").val(),
         SelectedDepartureCityAd: $("#SelectedDepartureCityAd").val(),
         SelectedFreeCalcTypeAd: $("#SelectedFreeCalcTypeAd").val(),
         profitAd: $("#profitAd").val(),
     };
     var DTO = JSON.stringify(QuotationAdvancedSearchViewModel);
     $.ajax({
         url: urls["QuotaAdvancedSearch"],
         type: 'POST',
         contentType: 'application/json; charset=utf-8',
         data: DTO,

         success: function (data) {
             $("#AdvancedSearchGrid").html(data);
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             //  $("#LoadingDiv").hide();
            
         }
     });
 }
 function AdvancedSearchRowClick(QuotaId) {
     $('#cboxClose').click();
     $('#Lookup').val(QuotaId);
     $('#QuotaGoButton').click();
 }

// Curency AutoComplete
// Hotel
 $(document).on('input', '.CurrencyHotel', function () {
     $("#HotelTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });
 // Lunch Dinner
 $(document).on('input', '.CurrencyLunchDinner', function () {
     $("#LunchTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });
 // Entrance
 $(document).on('input', '.CurrencyEntrance', function () {
     $("#EntranceTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });
 // Misc
 $(document).on('input', '.CurrencyMisc', function () {
     $("#MiscTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });
 // Bus
 $(document).on('input', '.CurrencyBus', function () {
     $("#BusTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });
 // Guide
 $(document).on('input', '.CurrencyGuide', function () {
     $("#GuideTabUpdate").addClass("QuotaDetDataChanged");
     var val = $(this).val().toUpperCase();
     var elem = $(this).attr('id');
     Currency.forEach(function (entry) {
         if (entry.indexOf(val) != -1) {
             $("#" + elem).val(entry);
             entry == "CA" ? $("#" + elem).addClass("QuotationCurrCAD") : $("#" + elem).removeClass("QuotationCurrCAD");
         }
     });
 });

// M checkbox
 $(document).on('change', '.QuotaRemTxtComplete', function () {
     var Itm = $(this).parent().prev().children()[0];
     if ($(this).is(":checked"))
     {
         if($(Itm).hasClass("QuotaTxtComplete"))
             $(Itm).removeClass("QuotaTxtComplete");
         $(Itm).next().val(null);
     }     
     else
     {
         if (!($(Itm).hasClass("QuotaTxtComplete")))
             $(Itm).addClass("QuotaTxtComplete");
     }
 });

 function BindBusServiceDrop() {
     $(".BusServiceDrop").each(function (index, elem) {
         $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
     });
 }
 $(document).on('change', '.BusServiceDrop', function () {
     $(this).next().prop("selectedIndex", $(this).prop("selectedIndex"));
 });
 function BindGuideServiceDrop() {
     $(".GuideServiceDrop").each(function (index, elem) {
         $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
     });
 }
 $(document).on('change', '.GuideServiceDrop', function () {
     $(this).next().prop("selectedIndex", $(this).prop("selectedIndex"));
 });

 // text element complete text 
 $(document).on('input', '.QuotaTxtComplete', function () {
     if (TimerId == null) {
         AutoComElem = $(this).attr('id');
         AutoComElemVal = $("#" + AutoComElem).val();
         TimerId = setInterval(function () {

             var keyword = $("#" + AutoComElem).val();
             if (keyword == AutoComElemVal) {
                 var PropName = "";
                 if (AutoComElem.indexOf("HotelDesc") != -1) {
                     PropName = "HotelDesc";
                     $("#" + AutoComElem).next().val(null);
                 }
                 if (AutoComElem.indexOf("DescriptionLunch") != -1 && $("#" + AutoComElem).hasClass("LunchDetTab")) {
                     PropName = "LunchDinner";
                     $("#" + AutoComElem).next().val(null);
                 }
                 if (AutoComElem.indexOf("DescriptionEntrance") != -1 && $("#" + AutoComElem).hasClass("EntranceDetTab")) {
                     PropName = "Entrance";
                     $("#" + AutoComElem).next().val(null);
                 }
                 if (AutoComElem.indexOf("DescriptionBus") != -1 && $("#" + AutoComElem).hasClass("BusDetTab")) {
                     PropName = "Bus";
                     $("#" + AutoComElem).next().val(null);
                 }
                 if (AutoComElem.indexOf("DescriptionGuide") != -1 && $("#" + AutoComElem).hasClass("GuideDetTab")) {
                     PropName = "Guide";
                     $("#" + AutoComElem).next().val(null);
                 }
                 if (AutoComElem.indexOf("InvCustomer") != -1 || AutoComElem.indexOf("AddGirCustomer") != -1) {
                     PropName = "GirCustomer";
                     $("#" + AutoComElem).next().val(null);
                 }
                 
                
                 var position = $("#" + AutoComElem).offset();
                 position.top = position.top + $("#" + AutoComElem).height()+5;
                 $.ajax({
                     url: urls["QuotaAutoComplete"],
                     data: { 'PropName': PropName, 'keyword': keyword },
                     type: 'POST',
                     success: function (data) {
                         $("#AutoCompleteDiv").html(data);
                         var width = $("#" + AutoComElem).css("width");
                         $("#AutoCompleteDiv").css("width", width);
                         $("#AutoCompleteDiv").show();
                         $("#AutoCompleteDiv").offset(position);
                     },
                     error: function (xhr) {
                         //  alert('Error: ' + xhr.statusText);
                     },
                     complete: function () {
                         clearInterval(TimerId);
                         TimerId = null;
                     }
                 });
             }
             else
                 AutoComElemVal = keyword;
         }, 600);
     }
 });
 $(document).on('click', '.QuotaAutoCompleteDivClose', function () {
     $(this).parent().parent().hide();
 });
 function htmlDecode(value) {
     return $('<div/>').html(value).text();
 }
 function AutoCompleteRowClick(key, val) {
     val = htmlDecode(val);
     $("#" + AutoComElem).val(val);
     if (AutoComElem.indexOf("InvCustomer") != -1 || AutoComElem.indexOf("AddGirCustomer") != -1)
         $("#" + AutoComElem).next().val(key);
     if (AutoComElem.indexOf("HotelDesc") != -1) {
         $("#" + AutoComElem).next().val(key);
         LoadVendorContract(key, "Hotel")
     }
     if (AutoComElem.indexOf("DescriptionBus") != -1) {
         $("#" + AutoComElem).next().val(key);
         LoadVendorContract(key, "Bus")
     }
     if (AutoComElem.indexOf("DescriptionEntrance") != -1) {
         $("#" + AutoComElem).next().val(key);
         LoadVendorContract(key, "Entrance")
     }
     if (AutoComElem.indexOf("DescriptionGuide") != -1) {
         $("#" + AutoComElem).next().val(key);
         LoadVendorContract(key, "Guide")
     }
     if (AutoComElem.indexOf("DescriptionLunch") != -1) {
         $("#" + AutoComElem).next().val(key);
         LoadVendorContract(key, "LunchDinner")
     }
     $("#AutoCompleteDiv").hide();
 }

 function LoadVendorContract(VendorID, Entity)
 {
     var DivContainer;
     if (Entity == "Hotel")
         DivContainer = $("#VendorContractHotel");
     if (Entity == "LunchDinner")
         DivContainer = $("#VendorContractLunchDinner");
     if (Entity == "Entrance")
         DivContainer = $("#VendorContractEntrance");
     if (Entity == "Misc")
         DivContainer = $("#VendorContractMisc");
     if (Entity == "Bus")
         DivContainer = $("#VendorContractBus");
     if (Entity == "Guide")
         DivContainer = $("#VendorContractGuide");

     $.ajax({
         url: urls["LoadVendorContractInfo"],
         type: 'GET',
         data: { 'VendorID': VendorID, 'SeasonID': $("#SelectedSeason").val()},
         success: function (data) {
               DivContainer.html(data);
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             DivContainer.show();
            // $("#VendorContractTbl").freezeHeader({ 'height': '100px' });
             if(Entity == "Hotel")
                 $("#VendorContractHotelProp").show();
         }
     });
 }
 

 $(document).on('click', '.QuotaTabs', function () {
     var ElemId = $(this).attr("href");
     if ($("#HotelTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabHotels") 
         jAlert('There is/are unsaved data in Hotels tab.', 'Attention!');
     if ($("#LunchTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabLunchDinner")
         jAlert('There is/are unsaved data in Lunch/Dinner tab.', 'Attention!');
     if ($("#EntranceTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabEntrance")
         jAlert('There is/are unsaved data in Entrance tab.', 'Attention!');
     if ($("#MiscTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabGrpMisc")
         jAlert('There is/are unsaved data in Group Misc tab.', 'Attention!');
     if ($("#BusTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabBus")
         jAlert('There is/are unsaved data in Bus/DeadHead tab.', 'Attention!');
     if ($("#GuideTabUpdate").hasClass("QuotaDetDataChanged") && ElemId != "#tabGuide")
         jAlert('There is/are unsaved data in Guide tab.', 'Attention!');
     if ($("#CalculateCostBtn").hasClass("QuotaDetDataChanged") && ElemId != "#tabCost")
         jAlert('There is/are unsaved data in Cost/Price tab.', 'Attention!');
     if (ElemId == "#tabCost" && $("#tabhrefCost").css("background-color") == "rgb(255, 0, 0)") {
         NightsValidation(true);
         MealsValidation(true);
     }

 });

// Gir functionality

 $(document).on('click', '#GroupIsGir', function () {
     if ($("#GroupIsGir").is(":checked")) {
         $("#QuotaGirGroupDiv").show();
         $("#QuotaNonGirGroupDiv").hide();
     }
     else
     {
         $("#QuotaGirGroupDiv").hide();
         $("#QuotaNonGirGroupDiv").show();
     }
 });

// Create non Gir Group
 function CreateGroupBtnClick()
 {
     $.ajax({
         url: urls["QuotationCreateNonGirGroup"],
         type: 'POST',
         success: function (GroupID) {
             $("#GroupID").val(GroupID);
             $("#GroupCode").val(GroupID);
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             jAlert($("#GrActionMessage").val(), 'Info!');
         }
     });
 }
// Save Non Gir Group
 function SaveGroupBtnClick() {
     var QuotationGroupDetailViewModel = {
         CustomerID: $("#SelectedCustomerId").val(),
         SeasonID: $("#SelectedSeason").val(),
         GroupID: $("#GroupID").val(),
         QuotaID: $("#QuotaIden").val(),
         GroupCode: $("#GroupCode").val(),
         GroupName: $("#GroupName").val(),
         GroupEstPax: $("#GroupEstPax").val(),
         GroupEstRooms: $("#GroupEstRooms").val(),
     };

     var DTO = JSON.stringify(QuotationGroupDetailViewModel);

     $.ajax({
         url: urls["QuotationSaveNonGirGroup"],
         type: 'POST',
         contentType: 'application/json; charset=utf-8',
         data: DTO,

         success: function (Error) {
             if (Error.Message != null)
                 jAlert(Error.Message, "Error!");
             else
                 jAlert("Group successfully created.", 'Successful');
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {

         }
     });
 }

// Create gir group
 function CreateGirGroupBtnClick() {
     $.ajax({
         url: urls["QuotationCreateGirGroup"],
         type: 'POST',
         data: { 'QuotaID': $("#QuotaIden").val() },
         success: function (data) {
             $("#QuotaGirGroupGridDiv").html(data);
             $("#AddGirNoNights").val($("#NoNights").val());  
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             GirGroupPopUp();
             BindGirNonGirGroupDrop();
         }
     });
 }

 // Create group Series
 function CreateGroupSeriesBtnClick() {
     $.ajax({
         url: urls["QuotationCreateGroupSeries"],
         type: 'POST',
         data: { 'QuotaID': $("#QuotaIden").val(), 'CustomerID': $("#SelectedCustomerId").val() },
         success: function (data) {
             $("#QuotaGirGroupGridDiv").html(data);
             $("#AddGirNoNights").val($("#NoNights").val());
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             GirGroupPopUp();
         }
     });
 }

// New Gir group
 $(document).on('click', '#SaveNewGirGroupBtn', function () {
     if (ValidateQuotaNewGirGroup()) {
         var FromServerValid = ValidateQuotaNewGirGroupFromServer();
         if (FromServerValid) {
             $('#IsNewGroup').val('True'); 
             $('#AddGirQuotaID').val($("#QuotaIden").val());
             $('#AddGirSeasonID').val($("#SelectedSeason").val());
             if ($("#GirGroupRowsCount").val() == 0) {
                 $("#GirGroupRowsCount").val('1');
             }
             $('#SaveGirGroupBtn').click();
         }
     }
 });
 // New Gir group Customer
 $(document).on('click', '#SaveNewGirGroupCustomerBtn', function () {
     if (ValidateQuotaNewGirGroupCustomer()) {
         $('#IsNewInv').val('True');
         $('#AddGirQuotaID').val($("#QuotaIden").val());
         $('#SaveGirInvoiceBtn').click();
     }
 });
 // All Gir groups save
 $(document).on('click', '#SaveGirGroupBtn', function () {
     if (!$('#SaveGirGroupBtn').hasClass('QuotaDetDataChanged'))
         return;
     if (ValidateQuotaGirGroup()) {
         if ($("#GirGroupRowsCount").val() > 0) {
             $('#IsSaveGroup').val('True');
             $('#AddGirQuotaID').val($("#QuotaIden").val());
         }
         else {
             jAlert("You have not data to save:", "Attention!");
         }
     }
 });
 // Gir Invoice save
 $(document).on('click', '#SaveGirInvoiceBtn', function () {
     //if (ValidateQuotaGirGroupCustomer()) {
         $('#IsSaveInvoice').val('True');
         $('#AddGirQuotaID').val($("#QuotaIden").val());
     //}
 });

 function InitGirGroupCalendars()
 {
     BindGirNonGirGroupDrop();
     $(".QuotaGirDate").datepicker({
         defaultDate: "+1w",
         minDate: 0,
         changeMonth: true,
         changeYear: true,
         numberOfMonths: 1,
         dateFormat: 'D, dd/M/y',
         beforeShow: function (input) {
             $(input).css({
                 "position": "relative",
                 "z-index": 999999
             });
         }
     });
 }
 function GirGroupPopUp()
 {
     var height = "700px";
     var width = "1445px";
     if ($("#IsGir").val() == "False") {
         height = "380px";
         width = "1345px";
     }
     $("#QuotaGirGroupGridDiv").show();
  $.colorbox({
     width: width,
     height: height,
     inline: true,
     href: "#QuotaGirGroupGridDiv",
     onComplete: function () {
         // init calendars
         $(".QuotaGirDate").datepicker({
             defaultDate: "+1w",
             minDate:0,
             changeMonth: true,
             changeYear: true,
             numberOfMonths: 1,
             dateFormat: 'D, dd/M/y',
             beforeShow: function (input) {
                 $(input).css({
                     "position": "relative",
                     "z-index": 999999
                 });
             }
         });    
     },
     onClosed: function () {
         $("#QuotaGirGroupGridDiv").hide();
     }
 });
 }
 
 function BindGirNonGirGroupDrop() {
     $(".GirNonGirStatusDrop").each(function (index, elem) {
         $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
     });
 }
 $(document).on('change', '.GirNonGirStatusDrop', function () {
     $(this).next().prop("selectedIndex", $(this).prop("selectedIndex"));
 });

// push Group to operation

 function GroupPushOperation(GroupID)
 {
     $.ajax({
         url: urls["QuotationPushOperationGroup"],
         type: 'POST',
         data: { 'GroupID': GroupID, 'Gir': $("#IsGir").val() },
         success: function (data) {
             $("#QuotaGirGroupGridDiv").html(data);
             $("#AddGirNoNights").val($("#NoNights").val());
         },
         error: function (xhr) {
             //   alert('Error: ' + xhr.statusText);
         },
         complete: function () {
             GirGroupPopUp();
             jAlert($("#GrActionMessage").val(), 'Info!');
         }
     });
 }
 function AddNewGirGroupDivHide()
 {
     $('#AddNewGirGroupDiv').hide();
     $('#GirGroupGridDiv').show();
     $('#SaveNewGirGroupBtn').removeClass('QuotaDetDataChanged');
 }
 function AddNewGirGroupCustomerDivHide() {
     $('#AddNewGirGroupCustomerDiv').hide();
     $('#GirGroupCustomerGridDiv').show();
     $('#SaveNewGirGroupCustomerBtn').removeClass('QuotaDetDataChanged');
 }
 function QuotaBusTabAjaxComplete()
 {
     QuotaValidateComplete();
     BindBusServiceDrop();
 }
 function QuotaGuideTabAjaxComplete() {
     QuotaValidateComplete();
     BindGuideServiceDrop();
 }
 function QuotaValidateComplete()
 {
     if ($("#QuotaHotelErrorCode").val() != "" && $("#QuotaHotelErrorCode").val() != "0")
     {
         if ($("#QuotaHotelErrorCode").val() == "4445") {
             jAlert($("#QuotaHotelErrorMessage").val(), "Warrning!");
             $("#QuotaHotelErrorCode").val("");
             $("#QuotaHotelErrorMessage").val("");
         }
     }
     if ($("#QuotaLunchDinnerErrorCode").val() != "" && $("#QuotaLunchDinnerErrorCode").val() != "0") {
         if ($("#QuotaLunchDinnerErrorCode").val() == "4445") {
             jAlert($("#QuotaLunchDinnerErrorMessage").val(), "Warrning!");
             $("#QuotaLunchDinnerErrorCode").val("");
             $("#QuotaLunchDinnerErrorMessage").val("");
         }
     }
     if ($("#QuotaEntranceErrorCode").val() != "" && $("#QuotaEntranceErrorCode").val() != "0") {
         if ($("#QuotaEntranceErrorCode").val() == "4445") {
             jAlert($("#QuotaEntranceErrorMessage").val(), "Warrning!");
             $("#QuotaEntranceErrorCode").val("");
             $("#QuotaEntranceErrorMessage").val("");
         }
     }
     if ($("#QuotaBusErrorCode").val() != "" && $("#QuotaBusErrorCode").val() != "0") {
         if ($("#QuotaBusErrorCode").val() == "4445") {
             jAlert($("#QuotaBusErrorMessage").val(), "Warrning!");
             $("#QuotaBusErrorCode").val("");
             $("#QuotaBusErrorMessage").val("");
         }
     }
     $("#CalculateCostBtn").click();
 }
 var originalClose = $.colorbox.close;
 $.colorbox.close = function () {
     if ($('#SaveGirGroupBtn').hasClass('QuotaDetDataChanged') || $('#SaveNewGirGroupBtn').hasClass('QuotaDetDataChanged') || $('#SaveGirInvoiceBtn').hasClass('QuotaDetDataChanged') || $('#SaveNewGirGroupCustomerBtn').hasClass('QuotaDetDataChanged')) {
         jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
             if (retVal == true) {
                 $("#QuotaGirGroupGridForm").empty();
                 originalClose();
             }
         });
     }
     else {
         $("#QuotaGirGroupGridForm").empty();
         originalClose();
     }
 };
 function LockUnLockQuotation() {
     var QuotaID = $("#QuotationID").val()
     $.ajax({
         url: urls["QuotationLockUnLock"],
         data: { 'QuotaId': parseInt(QuotaID) },
         type: 'POST',
         success: function (data) {
             if (data == "Yes")
             {
                 $("#QuotaLockUnLockButton").removeClass('btn-danger');
                 $("#QuotaLockUnLockButton").addClass('LockBackColorGreen');
                 $("#QuotaLockUnLockButton").val("Lock");
                 $("#QuotaLockUnLockButton").text("Lock");
                 jAlert("Quotation Successfully Unlocked:", "Successful");
             }
             else if (data == "No") {
                 $("#QuotaLockUnLockButton").removeClass('LockBackColorGreen');
                 $("#QuotaLockUnLockButton").addClass('btn-danger');
                 $("#QuotaLockUnLockButton").val("UnLock");
                 $("#QuotaLockUnLockButton").text("UnLock");
                 jAlert("Quotation Successfully Locked:", "Successful");
             }
             else
                 jAlert("Quotation is locked by " + data + ".", "Warning!");
         },
         error: function (xhr) {
             jAlert(xhr.statusText, "Error");
         },
         complete: function () {
         }
     });
 }